package edu.zut.cs.software.perfect.base.service.impl;

import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;

import org.springframework.transaction.annotation.Transactional;

import edu.zut.cs.software.perfect.base.dao.GenericTreeDao;
import edu.zut.cs.software.perfect.base.domain.BaseTreeEntity;
import edu.zut.cs.software.perfect.base.service.GenericTreeManager;

/**
 * @ClassName GenericTreeManagerImpl
 * @Description TODO
 * @Author liangying
 * @Date 2020年5月13日 下午4:34:43
 * @Version 1.0
 */
@Transactional
public class GenericTreeManagerImpl <T extends BaseTreeEntity<T, PK>, PK extends Serializable>
extends GenericManagerImpl<PK, T> implements GenericTreeManager<T, PK> {

	protected GenericTreeDao<T, PK> treeDao;
	

	@Override
	public List<T> getAncestors(PK courseId) {
		List<T> ancestors = new ArrayList<T>();
		T entity = this.treeDao.findById(courseId).get();
		T parent = entity.getParent();
		while (parent != null) { // 追述祖先
			ancestors.add(parent);
			entity = parent;
			parent = entity.getParent();
		}
		return ancestors;
	}

	@Override
	public List<T> getChildren(PK courseId) {
		T entity = this.treeDao.findById(courseId).get();
		return entity.getChildren();
	}

	@Override
	public List<T> getDescendants(PK courseId) {
		List<T> descendants = new ArrayList<T>();
		List<T> children = this.getChildren(courseId);
		if (children != null && children.size() > 0) { // 追加子孙
			descendants.addAll(children);
			for (T t : children) {
				List<T> descendants2 = this.getDescendants(t.getCourseId());
				descendants.addAll(descendants2);
			}
		}
		return descendants;
	}

	@Override
	public List<T> getRoot() {
		return this.treeDao.getRoot();
	}

}
